/*
 * futabatasksendpost.cpp
 *
 *  Created on: Sep 25, 2011
 *      Author: anonovermind <anonovermind@gmail.com>
 */

#include <QRegExp>
#include "futabatasksendpost.h"
#include "futabaagent.h"
#include "captchafetchers/captchafetcher.h"

namespace Wishmaster {

FutabaTaskSendPost::FutabaTaskSendPost(const PostDescriptor& post, const QString& captcha,
		Wishmaster2::Network::RequestManager* requestManager, const QString& msg, FutabaAgent* agent) :
		TaskSendPost(post, captcha, requestManager, msg),
		m_post(post),
		m_captcha(captcha),
		m_agent(agent)
{

}

FutabaTaskSendPost::~FutabaTaskSendPost() {
}

Wishmaster2::Network::RequestPtr FutabaTaskSendPost::makeRequest(const PostDescriptor& post, const QString& captcha, Wishmaster2::Network::RequestManager *requestManager)
{
		QString postscript = m_agent->property("postscript").toString();
		postscript.replace("%BOARD%", post.board);
		postscript.replace("%THREADID%", QString::number(post.parent_thread.threadNumericId()));

		QString wholehost = post.parent_thread.chanName();
		if(m_agent->property(QString("posthostprefix" + post.board).toUtf8().data()).isValid())
			wholehost.prepend(m_agent->property(QString("posthostprefix" + post.board).toUtf8().data()).toString());

		QString referer = post.parent_thread.chanName();
		if(m_agent->property(QString("hostprefix" + post.board).toUtf8().data()).isValid())
			referer.prepend(m_agent->property(QString("hostprefix" + post.board).toUtf8().data()).toString());

		Wishmaster2::Network::Url url("http://" + (wholehost + postscript).toStdString());
		Wishmaster2::Network::RequestPtr request = requestManager->createRequest(url);
		request->setParameter("http:method", "POST");
		request->setParameter("http:referer", QString("http://%1%2res/%3").arg(referer).arg(post.board)
				.arg(post.parent_thread.threadNumericId()).toStdString());

		request->setParameter("MAX_FILE_SIZE", "2097152");
		request->setParameter("resto", std::string(post.parent_thread.threadStringId().toUtf8().constData()));
		request->setParameter("name", std::string(post.name.toUtf8().constData()));
		request->setParameter("email", std::string(post.email.toUtf8().constData()));
		request->setParameter("sub", std::string(post.topic.toUtf8().constData()));
		request->setParameter("com", std::string(post.text.toUtf8().constData()));
		m_agent->addAttachments(request, post.attachments.count() > 0 ? post.attachments.at(0) : AttachmentDescriptor(), "upfile");
		request->setParameter("pwd", std::string(post.password.toUtf8().constData()));
		request->setParameter("mode", "regist");

		if(!captcha.isEmpty())
			m_agent->captchaFetcher()->processRequest(post, captcha, request);

		return request;
}

} /* namespace Wishmaster */
